//
//  BIDCalendarViewController.m
//  TestCalendar
//
//  Created by mal on 14-1-10.
//  Copyright (c) 2014年 mal. All rights reserved.
//

#import "BIDCalendarViewController.h"
#import "BIDCalCell.h"
#import "AppDelegate.h"
#import "BIDEditCalendarViewController.h"
#import "EventKitController.h"

#define CELL_IDENTIFIER @"caldendarIdentifier"

@interface BIDCalendarViewController ()

@end

@implementation BIDCalendarViewController
@synthesize eventKitController;
@synthesize headerView;
@synthesize preBtn;
@synthesize nextBtn;
@synthesize dateLabel;

@synthesize dataSourceArr;
@synthesize calCollectionView;
@synthesize myTableView;
@synthesize remindersArr;

@synthesize _curDate;
@synthesize _todayDate;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.title = @"个人提醒";
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    remindersArr = [[NSMutableArray alloc] init];
    //初始化eventKitController
    eventKitController = [[EventKitController alloc] init];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(remindersPermissionGranted) name:RemindersAccessGranted object:eventKitController];
    //
    dataSourceArr = [[NSMutableArray alloc] initWithCapacity:35];
    
    //
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addCalEvent)];
    
    [self initHeaderView];
    
    //设置Layout
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(45, 45);
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 1;
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    CGSize collectionViewSize = CGSizeMake(320, 229);
    calCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, headerView.frame.origin.y+headerView.frame.size.height+1, collectionViewSize.width, collectionViewSize.height) collectionViewLayout:flowLayout];
    calCollectionView.dataSource = self;
    calCollectionView.delegate = self;
    [calCollectionView setBackgroundColor:[UIColor colorWithCGColor:[UIColor lightGrayColor].CGColor]];
    
    //计算数据源
    [self initDataSource:[NSDate date]];
    //注册cell
    [calCollectionView registerClass:[BIDCalCell class] forCellWithReuseIdentifier:CELL_IDENTIFIER];
    [self.view addSubview:calCollectionView];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    headerView = nil;
    dataSourceArr = nil;
    calCollectionView = nil;
    eventKitController = nil;
    myTableView = nil;
    remindersArr = nil;
}

//
- (void)initHeaderView
{
    //显示当前年月
    NSDate *curDate = [NSDate date];
    _curDate = curDate;
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy'年'M'月'"];
    NSString *strCurDate = [df stringFromDate:curDate];
    dateLabel.text = strCurDate;
    [headerView setBackgroundColor:[UIColor colorWithRed:230.0f/255.0f green:230.0f/255.0f blue:230.0f/255.0f alpha:1.0f]];
    NSMutableArray *labelArr = [[NSMutableArray alloc] initWithCapacity:7];
    int bottomSpacing = 1;
    NSArray *arr = [[NSArray alloc] initWithObjects:@"周日", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六", nil];
    int labelWidth = headerView.frame.size.width/7+0.7;
    CGSize labelSize = CGSizeMake(labelWidth, 20.0f);
    for(int i=0; i<arr.count; i++)
    {
        CGRect labelFrame = CGRectMake(0, headerView.frame.size.height-bottomSpacing-labelSize.height, labelSize.width, labelSize.height);
        if(i==0)
        {
        }
        else
        {
            UILabel *preLabel = (UILabel*)[labelArr objectAtIndex:i-1];
            labelFrame.origin.x = preLabel.frame.origin.x+labelSize.width;
        }
        UILabel *label = [[UILabel alloc] initWithFrame:labelFrame];
        label.textAlignment = NSTextAlignmentCenter;
        label.text = @"1";
        [label setBackgroundColor:[UIColor colorWithRed:230.0f/255.0f green:230.0f/255.0f blue:230.0f/255.0f alpha:1.0f]];
        [label setTextColor:[UIColor blackColor]];
        [label setText:[arr objectAtIndex:i]];
        label.font = [UIFont systemFontOfSize:10.0f];
        label.layer.borderWidth = 0;
        [labelArr addObject:label];
        [headerView addSubview:label];
    }
}

//上一个月
- (IBAction)preBtnHandler:(id)sender
{
    NSArray *todayArr = [self getArrWithDate:_curDate];
    int day = [todayArr[2] intValue];
    NSDate *date = [NSDate dateWithTimeInterval:-60*60*24*day sinceDate:_curDate];
    _curDate = date;
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy'年'M'月'"];
    NSString *strCurDate = [df stringFromDate:date];
    dateLabel.text = strCurDate;
    [self initDataSource:date];
    
}

//下一个月
- (IBAction)nextBtnHandler:(id)sender
{
    NSArray *todayArr = [self getArrWithDate:_curDate];
    int day = [todayArr[2] intValue];
    int days = [self getDaysWithDate:_curDate];
    NSDate *date = [NSDate dateWithTimeInterval:60*60*24*(days-day+1) sinceDate:_curDate];
    _curDate = date;
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy'年'M'月'"];
    NSString *strCurDate = [df stringFromDate:date];
    dateLabel.text = strCurDate;
    [self initDataSource:date];
}

//是否为闰年
- (BOOL)isLeapYear:(NSDate*)date
{
    NSArray *arr = [self getArrWithDate:date];
    int year = [arr[0] intValue];
    if(year%100==0)
    {
        if(year%400==0)
        {
            return YES;
        }
        else
        {
            return NO;
        }
    }
    else
    {
        if(year%4==0)
        {
            return YES;
        }
        else
        {
            return NO;
        }
    }
    return NO;
}

//初始化数据源
- (void)initDataSource:(NSDate *)date1
{
    __block NSDate *date = date1;
    [self showSpinnerView];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        //移除之前的数据
        [dataSourceArr removeAllObjects];
        //根据参数date获得所在月份1号的date
        NSArray *srcArr = [self getArrWithDate:date];
        int srcDay = [srcArr[2] intValue];
        date = [NSDate dateWithTimeInterval:-60*60*24*(srcDay-1) sinceDate:date];
        NSArray *dateArr = [self getArrWithDate:date];
        BOOL bLeapYear = [self isLeapYear:date];
        //当前月共有多少天
        int days = 0;
        int month = [dateArr[1] intValue];
        switch(month)
        {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
            {
                days = 31;
            }
                break;
            case 4:
            case 6:
            case 9:
            case 11:
            {
                days = 30;
            }
                break;
            case 2:
            {
                days = bLeapYear?29:28;
            }
                break;
        }
        //当前月的1号是周几
        NSString *strWeekDay = dateArr[3];
        int weekday = 0;
        if([strWeekDay isEqualToString:@"周日"]) weekday = 0;
        else if([strWeekDay isEqualToString:@"周一"]) weekday = 1;
        else if([strWeekDay isEqualToString:@"周二"]) weekday = 2;
        else if([strWeekDay isEqualToString:@"周三"]) weekday = 3;
        else if([strWeekDay isEqualToString:@"周四"]) weekday = 4;
        else if([strWeekDay isEqualToString:@"周五"]) weekday = 5;
        else if([strWeekDay isEqualToString:@"周六"]) weekday = 6;
        //根据周几来判断日历显示的行数
        int rows = (days+(weekday-7)+7)%7==0?(days+(weekday-7))/7:(days+(weekday-7)+7)/7;
        rows+=1;
        //创建数据源
        int day = 0;
        for(int i=0; i<rows*7; i++)
        {
            if(i>=weekday && day<days)
            {
                day++;
                [dataSourceArr addObject:[NSNumber numberWithInt:day]];
            }
            else
            {
                [dataSourceArr addObject:@""];
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self hideSpinnerView];
            CGRect frame = calCollectionView.frame;
            frame.size.height = rows*45+(rows-1)*1;
            calCollectionView.frame = frame;
            
            CGSize screenSize = [UIScreen mainScreen].bounds.size;
            CGRect ownFrame = self.view.frame;
            ownFrame.size.height = screenSize.height - 64;
            self.view.frame = ownFrame;
            CGRect myTableViewFrame = myTableView.frame;
            myTableViewFrame.origin.y = calCollectionView.frame.origin.y + calCollectionView.frame.size.height;
            myTableViewFrame.size.height = ownFrame.size.height-8-myTableViewFrame.origin.y;
            myTableView.frame = myTableViewFrame;
            [calCollectionView reloadData];
        });
    });
}

- (int)getDaysWithDate:(NSDate *)date
{
    NSArray *dateArr = [self getArrWithDate:date];
    BOOL bLeapYear = [self isLeapYear:date];
    //当前月共有多少天
    int days = 0;
    int month = [dateArr[1] intValue];
    switch(month)
    {
        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:
        {
            days = 31;
        }
            break;
        case 4:
        case 6:
        case 9:
        case 11:
        {
            days = 30;
        }
            break;
        case 2:
        {
            days = bLeapYear?29:28;
        }
            break;
    }
    return days;
}

//以数组的形式获取年月日
- (NSArray*)getArrWithDate:(NSDate*)date
{
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy:M:d:EEE"];
    NSString *str = [df stringFromDate:date];
    return [str componentsSeparatedByString:@":"];
}

//添加提醒
- (void)addCalEvent
{
    BIDEditCalendarViewController *editCalViewController = [[BIDEditCalendarViewController alloc] initWithNibName:@"BIDEditCalendarViewController" bundle:nil];
    editCalViewController.kitController = eventKitController;
    [self.navigationController pushViewController:editCalViewController animated:YES];
}
//访问提醒获得授权
- (void)remindersPermissionGranted
{
    [eventKitController startBroadcastingModelChangedNotifications];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshView) name:RemindersModelChangedNotification object:eventKitController];
    [eventKitController fetchAllReminders];
    [self getDataArrForTableView];
}
//当系统提醒事项发生变化时，更新列表
- (void)refreshView
{
    [self getDataArrForTableView];
}

- (void)getDataArrForTableView
{
    [remindersArr removeAllObjects];
    NSArray *arr = eventKitController.reminders;
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy年M月d日 H:mm"];
    NSDateFormatter *df1 = [[NSDateFormatter alloc] init];
    [df1 setDateFormat:@"yyyy/M/d"];
    for(int i=0; i<arr.count; i++)
    {
        EKReminder *reminder = (EKReminder*)[arr objectAtIndex:i];
        NSDateComponents *compts = reminder.dueDateComponents;
        NSCalendar *calendar = [NSCalendar currentCalendar];
        NSDate *date = [calendar dateFromComponents:compts];
        NSString *strDate = [df1 stringFromDate:date];
        NSString *strCurDate = [df1 stringFromDate:_curDate];
        if([strDate isEqualToString:strCurDate])
        {
            NSString *strTime = [df stringFromDate:date];
            NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:reminder.title, @"title", strTime, @"time", reminder, @"reminder", nil];
            [remindersArr addObject:dictionary];
        }
    }
    [myTableView reloadData];
}

#pragma mark UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [dataSourceArr count];
}

- (UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger index = [indexPath row];
    BIDCalCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CELL_IDENTIFIER forIndexPath:indexPath];
    NSString *str = [[NSString alloc] initWithFormat:@"%@", [dataSourceArr objectAtIndex:index]];
    cell.dayLabel.text = str;
    NSArray *dateArr = [self getArrWithDate:[NSDate date]];
    NSArray *curDateArr = [self getArrWithDate:_curDate];
    //年月日都相同才说明是今天
    if([dateArr[2] isEqualToString:str] && [dateArr[0] isEqualToString:curDateArr[0]] && [dateArr[1] isEqualToString:curDateArr[1]])
    {
        [cell.dayLabel setBackgroundColor:[UIColor redColor]];
    }
    else
    {
        [cell.dayLabel setBackgroundColor:[UIColor colorWithRed:230.0f/255.0f green:230.0f/255.0f blue:230.0f/255.0f alpha:1.0f]];
    }
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger index = [indexPath row];
    NSString *str = [[NSString alloc] initWithFormat:@"%@", [dataSourceArr objectAtIndex:index]];
    if(str.length==0) return;
    NSArray *dateArr = [self getArrWithDate:[NSDate date]];
    BIDCalCell *cell = (BIDCalCell*)[collectionView cellForItemAtIndexPath:indexPath];
    if([dateArr[2] isEqualToString:str])
    {
    }
    else
    {
        [cell.dayLabel setBackgroundColor:[UIColor colorWithRed:100.0f/255.0f green:100.0f/255.0f blue:100.0f/255.0f alpha:1.0f]];
    }
    //设置_curDate
    int day = [cell.dayLabel.text intValue];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *compts = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:_curDate];
    [compts setDay:day];
    _curDate = [calendar dateFromComponents:compts];
    [self getDataArrForTableView];
}

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger index = [indexPath row];
    NSString *str = [[NSString alloc] initWithFormat:@"%@", [dataSourceArr objectAtIndex:index]];
    NSArray *dateArr = [self getArrWithDate:[NSDate date]];
    BIDCalCell *cell = (BIDCalCell*)[collectionView cellForItemAtIndexPath:indexPath];
    if([dateArr[2] isEqualToString:str])
    {
    }
    else
    {
        [cell.dayLabel setBackgroundColor:[UIColor colorWithRed:230.0f/255.0f green:230.0f/255.0f blue:230.0f/255.0f alpha:1.0f]];
    }
}

#pragma mark UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [remindersArr count];
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"identifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if(!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
    }
    NSUInteger row = [indexPath row];
    NSDictionary *dictionary = [remindersArr objectAtIndex:row];
    cell.textLabel.text = [dictionary objectForKey:@"title"];
    cell.detailTextLabel.text = [dictionary objectForKey:@"time"];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    BIDEditCalendarViewController *viewController = [[BIDEditCalendarViewController alloc] initWithNibName:@"BIDEditCalendarViewController" bundle:nil];
    viewController.bEdit = YES;
    NSUInteger row = [indexPath row];
    NSDictionary *dictionary = [remindersArr objectAtIndex:row];
    EKReminder *reminder = (EKReminder*)[dictionary objectForKey:@"reminder"];
    viewController.reminder = reminder;
    viewController.kitController = self.eventKitController;
    [self.navigationController pushViewController:viewController animated:YES];
}

@end
